#!usr/bin/env python
#coding=utf8

from django.shortcuts import render_to_response as base_render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpRequest
from django.utils import simplejson
from django.core.urlresolvers import reverse

from tuangou import config


def render_to_response(template, dictionary=None, context_instance=None, mimetype=None):
    if isinstance(context_instance, HttpRequest):
        context_instance = RequestContext(context_instance)
    if template.find('admin/') != 0:
        template = 'theme/%s/template/%s' % (config.THEME, template)
    return base_render_to_response(template, dictionary=dictionary, 
                                   context_instance=context_instance, mimetype=mimetype)
    
def json_response(data):
    response = HttpResponse(simplejson.dumps(data))
    response['Content-Type'] = 'application/json'
    return response

def static_file(*args, **kwargs):
    '''
    返回静态文件（贪方便暂时这样写）
    '''
    return base_render_to_response(*args, **kwargs)
    
def reverse_url(*args, **kwargs):
    """根据url映射名称和参数，或许相应的完整url路径
    如: reverse_url('movie-detail-info', args=[movie.id])
    """
    return u'%s%s' % (config.HOME_URL, reverse(*args, **kwargs))

def json_api(f):
    """json api view方法装饰器
    自动将view方法返回的对象转化成json格式返回
    增加success=True表示请求返回正确
    当发生异常的时候，自动包装结果
    {success:False, error:exception str}
    """
    def new_f(*args, **kwargs):
        try:
            result = f(*args, **kwargs)
            if isinstance(result, dict):
                if 'success' not in result:
                    result['success'] = True
            return json_response(result)
        except Exception, e:
            return json_response({'success': False, 'error': '%s: %s' % (type(e).__name__, e)})
    new_f.func_name = f.func_name
    new_f.__doc__ = f.__doc__
    return new_f